package com.mobile.driver.controls {
	import com.adobe.ep.notifications.Notification;
	import com.adobe.ep.notifications.NotificationAlertPolicy;
	import com.adobe.ep.notifications.NotificationEvent;
	import com.adobe.ep.notifications.NotificationIconType;
	import com.adobe.ep.notifications.NotificationManager;
	import com.mobile.driver.models.OrderMessage;
	
	import flash.events.EventDispatcher;
	import flash.events.StatusEvent;
	
	import mx.core.FlexGlobals;
	import mx.events.DynamicEvent; 
	import mx.messaging.ChannelSet;
	import mx.messaging.MultiTopicConsumer;
	import mx.messaging.channels.AMFChannel;
	import mx.messaging.channels.StreamingAMFChannel;
	import mx.messaging.events.MessageEvent;
	import mx.messaging.events.MessageFaultEvent;
	import mx.rpc.AsyncToken;
	import mx.rpc.events.FaultEvent;
	
	import spark.managers.PersistenceManager;

	[Bindable]
	[Event(name="message", type="mx.events.DynamicEvent")]
	[Event(name="configFault", type="mx.events.DynamicEvent")]
	public class Feed extends EventDispatcher {
		protected var persistenceManager:PersistenceManager = new PersistenceManager();
      private var notificationManager:NotificationManager;
		
		public var messageBrokerURL:String;
		
		public var channel:String = "streamingamf";
      public const NOTIFICATION_CODE:String = "MY_CUSTOM_NOTIFICATION";
		
		protected var consumer:MultiTopicConsumer;
      private var appURI:String = FlexGlobals.topLevelApplication.appURI;
		
		public function Feed() {
         try  {
            this.notificationManager = new NotificationManager();
            this.notificationManager.addEventListener(NotificationEvent.NOTIFICATION_ACTION, onNotificationActionEvent);	
            this.notificationManager.addEventListener(StatusEvent.STATUS, onNotificationStatusEvent);
         }
         catch (ae:ArgumentError) {
            return;
         }
		}
      
		public function subscribe():void {
			if (consumer)
				consumer.subscribe();
		}
	
		public function unsubscribe():void {
			if (consumer) {
	 			consumer.unsubscribe();
				consumer.disconnect();
			}
		}
		
		public function init():void {
			consumer = new MultiTopicConsumer();
			consumer.destination = "message-feed";
			var amfChannel:AMFChannel = new StreamingAMFChannel();
			amfChannel.uri = appURI + "messagebroker/" + channel;
			var cs:ChannelSet = new ChannelSet();
			cs.addChannel(amfChannel);
			consumer.channelSet = cs;
			consumer.addEventListener(MessageEvent.MESSAGE, messageHandler);
			consumer.addEventListener(FaultEvent.FAULT, consumer_fault);
         consumer.addSubscription(FlexGlobals.topLevelApplication.currentUser.phone);
			consumer.subscribe();
		}
		
		protected function messageHandler(event:MessageEvent):void {
			var body:OrderMessage = event.message.body as OrderMessage;
         dispatchMessageEvent("message", body);

         if ( !this.notificationManager || !this.notificationManager.isSupported ) {
            return;
         }				
         
         var n:Notification = createNewNotification(body);
         this.notificationManager.notifyUser(NOTIFICATION_CODE, n);
		}
		
		public function setConfig(messageBrokerURL:String, channel:String):void {
			if (messageBrokerURL != this.messageBrokerURL || channel != this.channel) {
				this.messageBrokerURL = messageBrokerURL;
				this.channel = channel;
				persistenceManager.setProperty("messageBrokerURL", messageBrokerURL);
				persistenceManager.setProperty("channel", channel);
				persistenceManager.save();
			}
		}
		
		public function loadConfig():void {
			if (!persistenceManager.load()) {
				dispatchFaultEvent("configFault", "配置错误", "Configure MessageBroker URL in Settings Tab");
				return;
			}
			
			var property:Object = persistenceManager.getProperty("messageBrokerURL");
			if (property) {
				messageBrokerURL = property.toString();
			}
			else {
				dispatchFaultEvent("configFault", "配置错误", "Please configure the MessageBroker URL in Settings Tab");
				return;
			}
			
			property = persistenceManager.getProperty("channel");
			if (property) {
				channel = property.toString();
			}
			else {
				dispatchFaultEvent("configFault", "配置错误", "Please configure channel in Settings Tab");
				return;
			}
		}
		
		protected function dispatchFaultEvent(type:String, faultString:String, faultDetail:String):void {
			var e:DynamicEvent = new DynamicEvent(type);
			e.faultString = faultString;
			e.faultDetail = faultDetail;
			dispatchEvent(e);
		}
      
      protected function dispatchMessageEvent(type:String, spec:*):void {
         var e:DynamicEvent = new DynamicEvent(type);
         e.spec = spec;
         dispatchEvent(e);
      }
      
      private function createNewNotification(obj:OrderMessage):Notification {
         var n:Notification = new Notification();
         
         n.tickerText = "收到新订单";
         n.title = "新订单";
         if (obj.type == OrderMessage.MESSAGE_TYPE_REALTIME) {
            n.body = "快速叫车订单";		
         }
         else {
            n.body = "预约叫车订单";		
         }
         
         // This action label appears in two places on iOS: on the action button of the notification dialog, and on the unlock slider when the device is locked.
         // If unset, the iOS default will be used. 
         n.actionLabel = "actionLabel";
         
         // Allows you to contorl whether an alert is dispathed with each notification, or just the first notification.
         n.alertPolicy = NotificationAlertPolicy.EACH_NOTIFICATION;
         
         // On Android, specifies whether the notification persists when the user taps it in the notification area
         n.cancelOnSelect = true;
         
         // On Android and iOS "...the app will be brought to the foreground if it was in the background or launched if it had been shutdown.
         // On iOS, the way to perform the action of a notification manifests itself as a button 
         // on the notification dialog that appears when a notification is fired and different
         // text on the unlock slider when the device is locked. 
         // On Android, the way to perform an action is not visible, it is performed by selecting 
         // the notification from the notification list (window shade)."
         n.hasAction = true;
         n.actionData = "customAction";
         
         // Allows you to set the Android notification icon
         n.iconType = NotificationIconType.MESSAGE;
         
         // On both Android and iOS, lets you set a number on the icon or application badge
         n.numberAnnotation = 0;
         
         // On Android, "ongoing" notifications aren't cleared with the clear button
         n.ongoing = false;
         
         // Android and iOS
         n.playSound = true;
         
         // On Android, alerts (sound and vibration) until acknowledged 
         n.repeatAlertUntilAcknowledged = false;
         
         // Only configurable on Android
         n.vibrate = true;
         
         return n;
      }
      
      private function onNotificationActionEvent(ne:NotificationEvent):void {				
      }
      
      private function onNotificationStatusEvent(ne:NotificationEvent):void {
      }
      
      protected function feedManager_fault(event:FaultEvent, token:AsyncToken):void {
         if (event.fault.faultDetail)
            dispatchFaultEvent("fault", event.fault.faultString, event.fault.faultDetail);
      }
      
      protected function consumer_fault(event:MessageFaultEvent):void {
         if (event.faultDetail)
            dispatchFaultEvent("fault", event.faultString, event.faultDetail);
      }
	}
}